﻿var lsInfo = {
  current: 1,
  pageSize: allPageSize,
  data: [],
  data1: [],
  totalRow: 0,
  totalPage: 0,
  oneDate: {},
  editState: false,
  calendar: []
};

// document.getElementById('nav').innerHTML = template('navs', navinfo2);

$('#nav li').eq(1).addClass('active');

var add = true;
var projectId = getUrlId().id;
var start = getUrlId().start.split('#').join(' ');
var end = getUrlId().end.split('#').join(' ');
function getUrlId() {
  var url = window.location.href;
  url = url.slice(url.lastIndexOf('/') + 1).split('#-#');
  return {
    id: url[0],
    start: url[1],
    end: url[2]
  }
}

var getList = function () {};
var getList1 = function () {};
var showCale = function () {};


$('#calendar').fullCalendar({
  header: {
    left: 'today prev,next',
    center: 'title',
    right: ''
  },
  handleWindowResize: false,
  eventLimit: true,
  monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
  dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
  today: ["今天"],
  firstDay: 1,
  titleFormat: 'YYYY年MM月',
  buttonText: {
    today: '本月',
    month: '月',
    week: '周',
    day: '日',
    prev: '上一月',
    next: '下一月'
  },
  /*loading: function (bool) {
   if (bool) {
   console.log('loading');
   } else {
   console.log('complete');
   }
   },*/
  dayClick: function (date, jsEvent, view) {//日期点击后弹出的jq ui的框，添加日程记录

  },
  eventClick: function (calEvent, jsEvent, view) {
    add = false;
    lsInfo.oneDate = lsInfo.calendar[calEvent.content];
    var v = lsInfo.oneDate;
    // console.log(JSON.stringify(v))
    getOneData(v);
  },
  eventAfterRender: function (event, element, view) {
  },
  events: function (start, end, timezone, callback) {
    var d = new Date(end);
    var year = d.getFullYear();
    var month = d.getMonth();
    var day = '01';
    if (month === 0) {
      year = year - 1;
      month = 12;
    }
    var date = year + '-' + month + '-' + day + ' 00:00';
    // console.log(date);
    getList1 = function (obj) {
      // 根据地址栏获取id

      $.ajax({
        cache: false,
        async: false,
        url: '/api/CommonApi?API=GetProjectSchedulesByDate',
        type: 'get',
        data: {
          ProjectID: projectId,
          Date: date
        },
        dataType: 'json',
        success: function (data) {
          // console.log(data)
          if (data.Success) {
            obj.callback(data);
          }
        }
      });
    };
    showCale = function () {
      getList1({
        callback: function (data) {
          var newData = data.ApiParamObj;
          setCalendarData(newData);
          lsInfo.data1 = newData;

          loading.hide();
        }
      });
    };
    showCale();
  }
});

getList = function (obj) {
  // 根据地址栏获取id

  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetProjectSchedules',
    type: 'get',
    data: {
      ProjectID: projectId,
      sorts: ' CreateTime DESC',
      pagesize: lsInfo.pageSize,
      page: lsInfo.current
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        obj.callback(data);
      }
    }
  });
};
getList({
  size: lsInfo.pageSize,
  index: lsInfo.current,
  callback: function (data) {
    // console.log(data)
    // console.log(JSON.stringify(data));
    var newData = data.ApiParamObj;
    // console.log(newData)
    // setCalendarData(newData);
    // if (!newData[0].length) {
    //   return false;
    // }
    for (var key in newData[0]) {
      newData[0][key].StartTime = new Date(newData[0][key].StartTime).pattern('yyyy/MM/dd');
      newData[0][key].EndTime = new Date(newData[0][key].EndTime).pattern('yyyy/MM/dd');
    }


    // 列表数据
    document.getElementById('tableList').innerHTML = template('list', newData[0]);
    // // 分页
    var pagesInfo = data.ApiParamObj;
    lsInfo.data = newData;
    lsInfo.totalRow = pagesInfo[0].totalRow;
    lsInfo.totalPage = pagesInfo[0].totalPage;

    // console.log(lsInfo)
    $('#totalRow').html(lsInfo.totalRow);
    pagesSet(lsInfo);
    setPageSize(lsInfo);
    loading.hide();
  }
});


// 渲染日历数据
function setCalendarData(data) {
  // var i = 0;
  lsInfo.calendar = data;
  $("#calendar").fullCalendar('removeEvents');
  for (var key in data) {
    // console.log(data[key])
    // console.log(key)
    // lsInfo.calendar.push({
    //   id: data[key].Name.ID,
    //   title: data[key].Name,
    //   start: moment(new Date(data[key].StartTime).pattern('yyyy-MM-dd 00:00')).format(),
    //   end: moment(new Date(data[key].EndTime).pattern('yyyy-MM-dd 24:00')).format()
    // });
    $("#calendar").fullCalendar('renderEvent', {
      id: data[key].Name.ID,
      title: data[key].Name,
      start: moment(new Date(data[key].StartTime).pattern('yyyy-MM-dd 00:00')).format(),
      end: moment(new Date(data[key].EndTime).pattern('yyyy-MM-dd 24:00')).format(),
      content: key
    }, false);
    // i++;
  }
  // console.log(lsInfo.calendar)

  // $("#calendar").fullCalendar('eventSources', lsInfo.calendar);
  // if (add) {
  //   $("#calendar").fullCalendar('addEventSource', lsInfo.calendar);
  // } else {
  //   console.log(lsInfo.calendar)
  //   // $("#calendar").fullCalendar('updateEvent', lsInfo.calendar);
  // }

  // console.log($("#calendar").fullCalendar('clientEvents'))
}


// getList({
//   size: lsInfo.pageSize,
//   index: lsInfo.current,
//   callback: function (data) {
//     // console.log(data)
//     // console.log(JSON.stringify(data));
//     var newData = data.ApiParamObj;
//     setCalendarData(newData);
//
//     // 列表数据
//     document.getElementById('tableList').innerHTML = template('list', newData);
//     // // 分页
//     // var pagesInfo = data.ApiParamObj;
//     lsInfo.data = newData;
//     // lsInfo.totalRow = pagesInfo[0].totalRow;
//     // lsInfo.totalPage = pagesInfo[0].totalPage;
//     // $('#totalRow').html(lsInfo.totalRow);
//     // pagesSet(lsInfo);
//     // setPageSize(lsInfo);
//     loading.hide();
//   }
// });


// 点击分页请求事件
var showPage = function (o) {
  // console.log(o)
  getList({
    size: o.pageSize,
    index: o.current,
    callback: function (data) {
      // console.log(data)
      // console.log(JSON.stringify(data));
      var newData = data.ApiParamObj;
      // for (var key in newData) {
      //   if (newData[key]['State'] === '????') {
      //     newData[key]['State'] = '';
      //   }
      // }
      for (var key in newData[0]) {
        newData[key][0].StartTime = new Date(newData[0][key].StartTime).pattern('yyyy/MM/dd');
        newData[key][0].EndTime = new Date(newData[0][key].EndTime).pattern('yyyy/MM/dd');
      }
      // setCalendarData(newData);
      // 列表数据
      document.getElementById('tableList').innerHTML = template('list', newData[0]);
      // 分页
      var pagesInfo = data.ApiParamObj;
      o.data = newData;
      o.totalRow = pagesInfo[0].totalRow;
      o.totalPage = pagesInfo[0].totalPage;

      $('#totalRow').html(o.totalRow);
      pagesSet(o);
      loading.hide();
    }
  });
};

// 获取项目人员
getProjectUser();
function getProjectUser() {
  $.ajax({
    url: '/api/CommonApi?API=PM_RUN_GetProjectUsers',
    type: 'get',
    data: {
      ProjectID: projectId
    },
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        // console.log(data)
        // console.log(JSON.stringify(data));
        var obj = {};
        var list = data.ApiParamObj;
        var i = 0;
        var l = list.length;

        for (; i < l; i++) {
          if (!obj[list[i].RoleType]) {
            obj[list[i].RoleType] = [];
          }
          // if (list[i].IsAllot === '已分配') {
            obj[list[i].RoleType].push(list[i].UserName);
          // }

        }

        var h = '';
        // var showKey = {
        //   PM: '项目经理',
        //   RUN: '项目执行',
        //   PP: '项目人员'
        // };

        var showKey = [
          '项目经理',
          '项目执行',
          '项目人员'
        ];

        var hArr = [
          obj['PM'],
          obj['RUN'],
          obj['PP']
        ];

        for (i = 0, l = hArr.length;i < l;i++) {
          h += '<p><span>' + showKey[i] + '：</span>' + hArr[i].join(', ') + '</p>';
        }

        /*for (var key in obj) {
          h += '<p><span>' + showKey[key] + '：</span>' + obj[key].join(', ') + '</p>';
        }*/

        document.getElementById('projectInfo').innerHTML = h;

      }
    }
  });
}

// 新增项目
$('#addProject').on('click', function () {
  add = true;
  $('#td1').val('');
  $('#td2').val('');
  $('#td3').val('');
  $('#td4').val('');
  $('#td5').val(0);
  $('#td6').val(0);
  $('#td7').val(0);
  $('#td8').val(0);
  $('#td9').val(0);
  $('#save').html('新增');
  $('#projectEdit').modal('show');
});

// 编辑项目
$('#table').on('click', '.editProject', function () {
  add = false;
  var index = $(this).parent().parent().index();
  lsInfo.oneDate = lsInfo.data[0][index];
  var v = lsInfo.oneDate;
  // console.log(JSON.stringify(v))
  getOneData(v);
  /*$('#td1').val(v.Name);
  $('#td2').val(v.Address);
  $('#td3').val(new Date(v.StartTime).pattern('yyyy-MM-dd'));
  $('#td4').val(new Date(v.EndTime).pattern('yyyy-MM-dd'));
  $('#td5').val(v.CityTrafficCost);
  $('#td6').val(v.DowntownTrafficCost);
  $('#td7').val(v.AccommodationCost);
  $('#td8').val(v.LivingCost);
  $('#td9').val(v.OtherCost);

  $('#save').html('修改');
  $('#projectEdit').modal('show');*/
});

function getOneData(v) {
  $('#td1').val(v.Name);
  $('#td2').val(v.Address);
  $('#td3').val(new Date(v.StartTime).pattern('yyyy-MM-dd'));
  $('#td4').val(new Date(v.EndTime).pattern('yyyy-MM-dd'));
  $('#td5').val(v.CityTrafficCost);
  $('#td6').val(v.DowntownTrafficCost);
  $('#td7').val(v.AccommodationCost);
  $('#td8').val(v.LivingCost);
  $('#td9').val(v.OtherCost);

  $('#save').html('修改');
  $('#projectEdit').modal('show');
}

// 删除
$('#table').on('click', '.delProject', function () {
  var index = $(this).parent().parent().index();
  lsInfo.oneDate = lsInfo.data[0][index];
  var v = lsInfo.oneDate;
  loading.show();
  console.log(v)
  // console.log(JSON.stringify(v))
  // 删除
  $.ajax({
    url: '/api/CommonApi?API=ProjectScheduleTableOp',
    type: 'post',
    data: {
      ApiParamObj: JSON.stringify({
        'ID': v.ID,
        'IsDelete': 1
      })
    },
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        console.log('del success');
        showCale();
        showPage(lsInfo);
        loading.hide();
      }
    }
  });
});

// 保存
$('#save').on('click', function () {

  var form = $('#projectEdit form');
  var v1 = form[0].td1.value;
  var v2 = form[0].td2.value;
  var v3 = form[0].td3.value;
  var v4 = form[0].td4.value;
  var v5 = form[0].td5.value;
  var v6 = form[0].td6.value;
  var v7 = form[0].td7.value;
  var v8 = form[0].td8.value;
  var v9 = form[0].td9.value;

  var validator = new Validator();
  validator.add(v1, [{
    strategy: 'isNonEmpty',
    errorMsg: '出差目的不能为空'
  }]);

  validator.add(v2, [{
    strategy: 'isNonEmpty',
    errorMsg: '地点不能为空'
  }]);

  validator.add(v3, [{
    strategy: 'isNonEmpty',
    errorMsg: '执行开始时间不能为空'
  }]);

  validator.add(v4, [{
    strategy: 'isNonEmpty',
    errorMsg: '执行结束时间不能为空'
  }]);

  validator.add(v5, [{
    strategy: 'isNonEmpty',
    errorMsg: '城市间交通费用不能为空'
  }, {
    strategy: 'isRMB',
    errorMsg: '城市间交通费用必须为数字'
  }]);

  validator.add(v6, [{
    strategy: 'isNonEmpty',
    errorMsg: '市内交通费用不能为空'
  }, {
    strategy: 'isRMB',
    errorMsg: '市内交通费用必须为数字'
  }]);

  validator.add(v7, [{
    strategy: 'isNonEmpty',
    errorMsg: '住宿费用不能为空'
  }, {
    strategy: 'isRMB',
    errorMsg: '住宿费用必须为数字'
  }]);

  validator.add(v8, [{
    strategy: 'isNonEmpty',
    errorMsg: '包干费用不能为空'
  }, {
    strategy: 'isRMB',
    errorMsg: '包干费用必须为数字'
  }]);

  validator.add(v9, [{
    strategy: 'isNonEmpty',
    errorMsg: '其他费用不能为空'
  }, {
    strategy: 'isRMB',
    errorMsg: '其他费用必须为数字'
  }]);


  var errmsg = validator.start();
  if (errmsg) {
    alert(errmsg);
    return false;
  }

  var submitData = {
    ProjectID: projectId,
    Name: v1,
    Address: v2,
    StartTime: v3,
    EndTime: v4,
    CityTrafficCost: v5,
    DowntownTrafficCost: v6,
    AccommodationCost: v7,
    LivingCost: v8,
    OtherCost: v9
  };

  var ajaxType = '';
  if (add) {
    ajaxType = 'put';
  } else {
    ajaxType = 'post';
    submitData.ID = lsInfo.oneDate.ID;
  }
  // console.log(submitData)
  $.ajax({
    url: '/api/CommonApi?API=ProjectScheduleTableOp',
    type: ajaxType,
    data: {
      ApiParamObj: JSON.stringify(submitData)
    },
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        // console.log('success');
        showCale();
        showPage(lsInfo);
        $('#projectEdit').modal('hide');
      }
    }
  });
});
start = start.split(' ')[0];
end = end.split(' ')[0];
// console.log(start, end)
/*$('.input-daterange input').datepicker({
  // bootcssVer: 3,
  // todayBtn: true,
  todayBtn: 'linked',
  weekStart: 0,
  // autoclose: 1,
  autoclose: true,
  // todayHighlight: 1,
  // startView: 2,
  startView: 0,
  startDate: start,
  endDate: end,
  format: 'yyyy-mm-dd',
  // forceParse: 1,
  // showMeridian: 1,
  language: 'zh-CN',
  // minView: 2
  minView: 0
});*/
$('.input-daterange input').datetimepicker({
  bootcssVer: 2,
  todayBtn: true,
  weekStart: 0,
  autoclose: 1,
  startView: 2,
  startDate: start,
  endDate: end,
  format: 'yyyy-mm-dd',
  language: 'zh-CN',
  minView: 2
});